package com.example.wifi_test;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.GradientDrawable;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.LinearLayoutCompat;

import com.google.android.material.internal.BaselineLayout;
import com.google.android.material.internal.FlowLayout;

import java.util.ArrayList;
import java.util.List;

public class WifiDialog extends Dialog {
    private final Bundle data;
    private final Context context;
    private List<ScanResult> wifis;
    private WIFIUtils wifi;
    private LinearLayout warp;
    public WifiDialog(@NonNull Context ct,Bundle b) {
        super(ct);
        data = b;
        context = ct;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog);
        TextView titleView = findViewById(R.id.title_view);
        titleView.setText(data.getString("title"));
        warp = findViewById(R.id.wifis);
        //权限检查
        String[] permissions = {
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_WIFI_STATE,
        };
        if (PermissionUtils.check(context, permissions)) {
            System.out.println("已授权");

        } else {
            showMsg("wifi管理需要开启位置权限才能使用！");
            System.out.println("未授权");
            return;
        }
        wifi = new WIFIUtils(context);
        //搜索
        try {
            scan();
        }catch (Exception e){
            showMsg("wifi搜索失败，请稍后重试！");
            Log.e("wifi","wifi搜索失败");
        }

    }

    /**
     * 连接指定wifi
     * @param s wifi信息
     */
    private void alert(ScanResult s) {
        //已经连接过
        List<WifiConfiguration> list = wifi.getConfig();
        for (WifiConfiguration wf:list){
            if(wf.SSID.replace("\"","").equals(s.SSID)){
                //不需要弹窗
                try {
                    wifi.connect(s.SSID,"");
                }catch (Exception e){
                    showMsg("连接失败，请稍后重试！");
                    Log.e("wifi","连接失败");

                }
                this.hide();
                return;
            }
        }
        final EditText inputServer = new EditText(context);
        inputServer.setHint("请输入WIFI密码");
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(s.SSID).setIcon(R.drawable.pswd).setView(inputServer).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                String text = inputServer.getText().toString().trim();
                if(text.length()<8){
                    showMsg("密码不小于8位！");
                    return;
                }
                try {
                    wifi.connect(s.SSID,text);
                }catch (Exception e){
                    showMsg("连接失败，请稍后重试！");
                }

            }
        });
        builder.show();
    }
    /**
     * 提示信息
     * @param msg 信息
     */
    private void showMsg(String msg){
        Toast.makeText(context,msg,Toast.LENGTH_LONG).show();
    }
    public void scan() {

        wifi.scan(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent.getBooleanExtra(WifiManager.EXTRA_RESULTS_UPDATED,false)){
                    listRender();

                }
            }
        });
    }
    private String getLevel(int l){
        String[] str = {"▁","▂","▃","▄","▅"};
        int max = 5;
        float lenF = (float) l/100*max;
        int len = (int) Math.floor(lenF);
        if(len>=str.length){
            len = str.length-1;
        }
//        for (int i = 0; i < len; i++) {
//            s.append('■');
//        }
        return str[len];
    }
    private int getLevelIcon(int l){
        int[] icon = {R.drawable.wifi1,R.drawable.wifi2,R.drawable.wifi3,R.drawable.wifi4,R.drawable.wifi5};
        int max = 5;
        float lenF = (float) l/100*max;
        int len = (int) Math.floor(lenF);
        if(len>=icon.length){
            len = icon.length-1;
        }
        return icon[len];
    }
    /**
     * 列表渲染
     */
    private void listRender(){
        warp.removeAllViews();
        WifiInfo info = wifi.getConnectionInfo();

        for (ScanResult s : wifi.getList()){
            String title = s.SSID;
            if(title==null||title.equals("")){
                //title = "未知网络/隐藏网络";
                continue;
            }

            //列表

            LinearLayout box = new LinearLayout(context);
            box.setPadding(0,10,10,5);
            box.setOrientation(LinearLayout.VERTICAL);
            //列表上部分
            LinearLayout titleBox = new LinearLayout(context);
            //信号图标
            ImageView img = new ImageView(context);
            img.setImageResource(getLevelIcon(wifi.calculateSignalLevel(s.level,100)));
            img.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
            img.setBaselineAlignBottom(true);
            img.setLayoutParams(new FrameLayout.LayoutParams(20,20));
            titleBox.addView(img);
            //标题
            TextView t = new TextView(context);
            t.setTextAlignment(View.TEXT_ALIGNMENT_VIEW_START);
            t.setText(title);
            t.setPadding(10,5,5,5);
            titleBox.addView(t);
            box.addView(titleBox);

            //加密图标
            ImageView img2 = new ImageView(context);

            img2.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
            if(s.capabilities.contains("WPA")||s.capabilities.contains("WEP")){
                img2.setImageResource(R.drawable.pswd);
            }else{
                img2.setVisibility(View.GONE);
            }

            img2.setBaselineAlignBottom(true);
            img2.setLayoutParams(new FrameLayout.LayoutParams(20,20));
            titleBox.addView(img2);
            //按钮
            LinearLayout contr = new LinearLayout(context);
            Button btn1 = new Button(context);
            //当前连接的wifi
            if(s.SSID.equals(info.getSSID().replace("\"",""))){
                //高亮显示
                t.setTextColor(Color.rgb(0,150,0));
                t.setTypeface(Typeface.DEFAULT_BOLD);
                //隐藏连接按钮
                btn1.setVisibility(View.GONE);
                //连接图标
                img2.setImageResource(R.drawable.ok);
                img2.setVisibility(View.VISIBLE);
            }
            btn1.setText("连 接");
            btn1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //连接
                    alert(s);
                }
            });
            contr.addView(btn1);
            if(wifi.isSave(s.SSID)){
                Button btn2 = new Button(context);
                btn2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //忘记网络
                        try{
                            wifi.forget(s.SSID);
                            showMsg("已忘记此连接，下次需要重新输入密码！");
                        }catch (Exception e){
                            showMsg("操作失败，请重试！");
                        }
                    }
                });
                btn2.setText("忘 记");
                contr.addView(btn2);
            }

            contr.setVisibility(View.GONE);
            box.addView(contr);

            warp.addView(box);
            box.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    contrRender(view);
                }
            });
        }
    }
    /**
     * 列表控制按钮
     * @param view 被激活的视图
     */
    private void contrRender(View view){
        LinearLayout v = (LinearLayout)view;
        LinearLayout btns = (LinearLayout)v.getChildAt(1);
        if(btns!=null){
            if(btns.getVisibility()==View.VISIBLE){
                btns.setVisibility(View.GONE);
                v.setBackgroundColor(Color.TRANSPARENT);
                return;
            }else{
                btns.setVisibility(View.VISIBLE);
            }

        }else{
            return;
        }
        v.setBackgroundColor(Color.rgb(240,240,240));
        //隐藏其他
        int len = warp.getChildCount();
        for (int i = 0; i < len; i++) {
            LinearLayout item = (LinearLayout)warp.getChildAt(i);
            if(v.equals(item)){
                continue;
            }
            if(item!=null){
                item.setBackgroundColor(Color.TRANSPARENT);
                LinearLayout itemContr = (LinearLayout)item.getChildAt(1);
                if(itemContr!=null){
//                                            Log.d("TAG", "隐藏");
                    itemContr.setVisibility(View.GONE);
                }
            }

        }
    }
}
